<?php
/**
 * Description of XmlValidator
 *
 * @author Jason
 */

class XmlValidator {

  protected $schemaFile;
  protected $xmlStr;
  protected $xmlFile;

  protected $dom;  // the xml loaded into DOM XML object

  protected $debug = false;
  protected $error_str = "";  
  protected $errors_exist = false;

  public function __construct($schemaFile, $xmlStr, $debug = false) {
    $this->schemaFile = $schemaFile;
    $this->xmlStr = $xmlStr;
    
    // Enable user error handling 
    libxml_use_internal_errors(true); 
    
    $this->dom = new DOMDocument();
    $this->dom->loadXML($xmlStr);
    
    $this->debug = $debug;
    
  } /////////// end constructor //////



  public function validateVerbose() {
    
    $this->printD( "\n<h2>PHP XML Data Validator</h2>");
    $this->printD( "\n<p>For Schema <strong>". $this->schemaFile . "</strong>:<p/>"); 
 
    if (!$this->dom->schemaValidate($this->schemaFile)) { 
      $this->errors_exist = true;
      $this->printD( '\n<br/><b>Errors Found!</b><br/>'); 
      $this->libxml_display_errors(); 
      
      return $this->error_str;
    } 
    else { 
      $this->printD( "\n<p>File <strong style='color:blue;'>validated</strong> <p/>"); 
      
      return true;
    }   
    
  } //////////// end function validateVerbose() //////


  protected function printD($str) {
		if($this->debug) print($str);
    if($this->errors_exist) {
      $this->error_str .= $str;
    }
    
	} /////// end function printD() /////



  protected function libxml_display_error($error)   {
    
    // $this->printD( "<br/>At the top of libxml_display_error()<br/>");
    $retval = "<br/>\n"; 

    switch ($error->level) { 
      case LIBXML_ERR_WARNING: 
        $retval .= "<b>Warning $error->code</b>: "; 
        break; 
      case LIBXML_ERR_ERROR: 
        $retval .= "\n<b>Error $error->code</b>: "; 
        break; 
      case LIBXML_ERR_FATAL: 
        $retval .= "<b>Fatal Error $error->code</b>: "; 
        break; 
    }

    $retval .= trim($error->message); 

    if ($error->file) { 
      $retval .= " in <b>$error->file</b>"; 
    }

    $retval .= " on line <b>$error->line</b>\n"; 

    return $retval; 
  } /////////// end function libxml_display_error() //////////

  protected function libxml_display_errors() { 

    $errors = libxml_get_errors(); 

    //$this->printD( count($errors) . " errors were found.");
    
    foreach ($errors as $error) { 
      $this->printD( $this->libxml_display_error($error)); 
    } 
    libxml_clear_errors(); 
  } //////// end function libxml_display_errors() /////////////
  
  
} ////////////// end class ///////////////////////////////////

?>
